package com.qcby.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qcby.dao.ExamDao;
import com.qcby.dao.StudentDao;
import com.qcby.dao.StudentExamDao;
import com.qcby.entity.*;
import com.qcby.service.DeepSeekService;
import com.qcby.service.ExamService;
import com.qcby.service.QuestionService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExamServiceImpl implements ExamService {
    @Autowired
    private ExamDao examDao;
    @Autowired
    private DeepSeekService deepSeekService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private StudentExamDao studentExamDao;
    @Autowired
    private StudentDao studentDao;
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public PageResult<Exam> getExam(Exam exam) {
        examDao.updateExam(exam.getCreator());
        PageHelper.startPage(exam.getPage(),exam.getPageSize());
        List<Exam> page1 = examDao.getExam(exam);
        Page<Exam> page2 = (Page<Exam>) page1;
        PageResult<Exam> pageResult = new PageResult<>(page2.getTotal(),page2.getResult());
        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Result addExam(Exam exam) throws IOException {
        exam.setCreatetime(LocalDateTime.now());
        if(!exam.getType().equals("教师发布")){
            exam.setExamtime(LocalDateTime.now());
            exam.setStatus("进行中");
        }else{
            if (LocalDateTime.now().isBefore(exam.getExamtime())) {
                exam.setStatus("未开始");
            } else if (LocalDateTime.now().isBefore(exam.getExamtime().plusMinutes(exam.getDuration()))) {
                exam.setStatus("进行中");
            } else {
                exam.setStatus("已结束");
            }
        }
        examDao.addExam(exam);
        String name = exam.getName();
        String remark=exam.getRemark();
        String difficulty = exam.getDifficulty();
        String subject = exam.getSubject();
        Integer totalScore = exam.getTotalScore();
        Integer xuanzeNum=exam.getQuestions().get(0).getCount();
        Integer xuanzeScore=exam.getQuestions().get(0).getScore();
        Integer tiankongNum=exam.getQuestions().get(1).getCount();
        Integer tiankongScore=exam.getQuestions().get(1).getScore();
        Integer judgeNum=exam.getQuestions().get(2).getCount();
        Integer judgeScore=exam.getQuestions().get(2).getScore();
        Integer jiandaNum=exam.getQuestions().get(3).getCount();
        Integer jiandaScore=exam.getQuestions().get(3).getScore();
        Integer computingNum=exam.getQuestions().get(4).getCount();
        Integer computingScore=exam.getQuestions().get(4).getScore();
        List<ErrorCollection> errorCollections = exam.getWrongQuestions();
        String query = "这是我生成试卷的要求，试卷名称是"+name+",试卷科目是"+subject+"，试卷的难易程度是"+difficulty+",试卷总分是"+totalScore+",选择题目数量是"+xuanzeNum+",选择题分值是"+xuanzeScore+"，填空题目数量是"+tiankongNum+",填空题分值是"+tiankongScore+",判断题目数量是"+judgeNum+",判断题分值是"+judgeScore+",简答题数量是"+jiandaNum+",简答题分值是"+jiandaScore+",计算题目数量是"+computingNum+",计算题分值是"+computingScore+"，错题集是"+errorCollections+",请帮我按下面的要求生成一份试卷，需要包含content试题内容，type试题类型，score，该题的分数，如果是选择题则返回1. 下列哪个数是质数？[\"A. 12\", \"B. 15\", \"C. 17\", \"D. 21\"] 2 选择题，填空题是 21. 三角形内角和等于______度。 3  填空题，判断题是36. 所有偶数都是合数。[\"正确\", \"错误\"]   1   判断题，计算题是46. 解方程组：\n" +
                "2x + 3y = 7\n" +
                "3x - y = 5  10   计算题  返回形式为json对象如下格式{\n" +
                "  \"1\": {\n" +
                "    \"content\": \"下列哪个是质数？\",\n" +
                "    \"type\": \"选择题\",\n" +
                "    \"score\": 2,\n" +
                "    \"options\": [\"A. 12\", \"M. 15\", \"C. 17\", \"D. 21\"]\n" +
                "  },\n" +
                "  \"2\": {\n" +
                "    \"content\": \"三角形内角和等于______度\",\n" +
                "    \"type\": \"填空题\",\n" +
                "    \"score\": 3,\n" +
                "    \"options\": null\n" +
                "  },\n" +
                "  \"3\": {\n" +
                "    \"content\": \"所有偶数都是合数\",\n" +
                "    \"type\": \"判断题\",\n" +
                "    \"score\": 1,\n" +
                "    \"options\": [\"正确\", \"错误\"]\n" +
                "  },\n" +
                "  \"4\": {\n" +
                "    \"content\": \"解方程组：2x + 3y = 7\\n3x - y = 5\",\n" +
                "    \"type\": \"计算题\",\n" +
                "    \"score\": 10,\n" +
                "    \"options\": null\n" +
                "  }\n" +
                "}只用返回上述的json数据形式返回。所有条件符合,请严格按照题目的数量生成，不要缺少题目数量。每种类型的题生成对应的数量,确保一定是json数据";
        System.out.println(query);
        String json = deepSeekService.getJson(query);
        JSONObject jsonObject = new JSONObject(json);
        String res = jsonObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
        System.out.println(res);
        String questions = res.substring(7, res.length()-3);
        List<Question> questionList = new ArrayList<>();
        JSONObject jsonObject1 = new JSONObject(questions);
        for(int i = 0;i<jsonObject1.length();i++){
            Question question = new Question();
            question.setContent(jsonObject1.getJSONObject(String.valueOf(i+1)).getString("content"));
            question.setType(jsonObject1.getJSONObject(String.valueOf(i+1)).getString("type"));
            question.setScore(jsonObject1.getJSONObject(String.valueOf(i+1)).getInt("score"));
            if (jsonObject1.getJSONObject(String.valueOf(i+1)).isNull("options")||jsonObject1.getJSONObject(String.valueOf(i+1)).get("options")== null) {
                question.setOptions(null);  // 填空题、简答题等无选项
            } else {
                JSONArray optionsArray = jsonObject1.getJSONObject(String.valueOf(i+1)).getJSONArray("options");
                question.setOptions(optionsArray.toString());  // 将 JSONArray 转为字符串
            }
            question.setEid(exam.getId());
            questionList.add(question);
        }
        System.out.println(questionList);
        questionService.insertQuestions(questionList);
        StudentExam studentExam = new StudentExam();
        if (exam.getType().equals("教师发布")){
//            教师发布的情况
            List<Integer> list = studentDao.findAllStudentIds();
            studentExam.setStatus(exam.getStatus());
            studentExam.setEid(exam.getId());
            for(Integer id:list){
                studentExam.setSid(id);
                studentExam.setStatus(exam.getStatus());
                studentExamDao.insertStudentExam(studentExam);
            }
        }else{
//            笔记生成考试，错题生成考试的情况
            studentExam.setEid(exam.getId());
            studentExam.setStatus("进行中");
            studentExam.setSid(exam.getSid());
            studentExamDao.insertStudentExam(studentExam);
        }
        return Result.success();
    }

    @Override
    public Exam getExamById(Integer id) {
        return examDao.getExamById(id);
    }

    @Override
    public void updateExambyId(Integer id) {
        examDao.updateExambyId(id);
    }

    @Override
    public Result addExamByLessionPlan(LessonPlan plan) throws IOException {
        Exam exam = new Exam();
//        设计exam的信息
        exam.setCreatetime(LocalDateTime.now());
        exam.setType("教师发布");
//        将试卷的信息添加到数据库中
        exam.setCreator(plan.getCreator());
        exam.setName(plan.getName());
//        exam.setDuration(plan.getTime());

        examDao.addExam(exam);
        String name = exam.getName();
        String remark=exam.getRemark();
        String difficulty = exam.getDifficulty();
        String subject = exam.getSubject();
        Integer totalScore = exam.getTotalScore();
        Integer xuanzeNum=exam.getQuestions().get(0).getCount();
        Integer xuanzeScore=exam.getQuestions().get(0).getScore();
        Integer tiankongNum=exam.getQuestions().get(1).getCount();
        Integer tiankongScore=exam.getQuestions().get(1).getScore();
        Integer judgeNum=exam.getQuestions().get(2).getCount();
        Integer judgeScore=exam.getQuestions().get(2).getScore();
        Integer jiandaNum=exam.getQuestions().get(3).getCount();
        Integer jiandaScore=exam.getQuestions().get(3).getScore();
        Integer computingNum=exam.getQuestions().get(4).getCount();
        Integer computingScore=exam.getQuestions().get(4).getScore();
        String query = "这是我生成试卷的要求，试卷名称是"+name+",试卷科目是"+subject+"，试卷的难易程度是"+difficulty+",试卷总分是"+totalScore+",选择题目数量是"+xuanzeNum+",选择题分值是"+xuanzeScore+"，填空题目数量是"+tiankongNum+",填空题分值是"+tiankongScore+",判断题目数量是"+judgeNum+",判断题分值是"+judgeScore+",简答题数量是"+jiandaNum+",简答题分值是"+jiandaScore+",计算题目数量是"+computingNum+",计算题分值是"+computingScore+"，请帮我按下面的要求生成一份试卷，需要包含content试题内容，type试题类型，score，该题的分数，如果是选择题则返回1. 下列哪个数是质数？[\"A. 12\", \"B. 15\", \"C. 17\", \"D. 21\"] 2 选择题，填空题是 21. 三角形内角和等于______度。 3  填空题，判断题是36. 所有偶数都是合数。[\"正确\", \"错误\"]   1   判断题，计算题是46. 解方程组：\n" +
                "2x + 3y = 7\n" +
                "3x - y = 5  10   计算题  返回形式为json对象如下格式{\n" +
                "  \"1\": {\n" +
                "    \"content\": \"下列哪个是质数？\",\n" +
                "    \"type\": \"选择题\",\n" +
                "    \"score\": 2,\n" +
                "    \"options\": [\"A. 12\", \"M. 15\", \"C. 17\", \"D. 21\"]\n" +
                "  },\n" +
                "  \"2\": {\n" +
                "    \"content\": \"三角形内角和等于______度\",\n" +
                "    \"type\": \"填空题\",\n" +
                "    \"score\": 3,\n" +
                "    \"options\": null\n" +
                "  },\n" +
                "  \"3\": {\n" +
                "    \"content\": \"所有偶数都是合数\",\n" +
                "    \"type\": \"判断题\",\n" +
                "    \"score\": 1,\n" +
                "    \"options\": [\"正确\", \"错误\"]\n" +
                "  },\n" +
                "  \"4\": {\n" +
                "    \"content\": \"解方程组：2x + 3y = 7\\n3x - y = 5\",\n" +
                "    \"type\": \"计算题\",\n" +
                "    \"score\": 10,\n" +
                "    \"options\": null\n" +
                "  }\n" +
                "}只用返回上述的json数据形式返回。所有条件符合,请严格按照题目的数量生成，不要缺少题目数量。每种类型的题生成对应的数量,确保一定是json数据";
        System.out.println(query);
        String json = deepSeekService.getJson(query);
        JSONObject jsonObject = new JSONObject(json);
        String res = jsonObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
        System.out.println(res);
        String questions = res.substring(7, res.length()-3);
        List<Question> questionList = new ArrayList<>();
        JSONObject jsonObject1 = new JSONObject(questions);
        for(int i = 0;i<jsonObject1.length();i++){
            Question question = new Question();
            question.setContent(jsonObject1.getJSONObject(String.valueOf(i+1)).getString("content"));
            question.setType(jsonObject1.getJSONObject(String.valueOf(i+1)).getString("type"));
            question.setScore(jsonObject1.getJSONObject(String.valueOf(i+1)).getInt("score"));
            if (jsonObject1.getJSONObject(String.valueOf(i+1)).isNull("options")||jsonObject1.getJSONObject(String.valueOf(i+1)).get("options")== null) {
                question.setOptions(null);  // 填空题、简答题等无选项
            } else {
                JSONArray optionsArray = jsonObject1.getJSONObject(String.valueOf(i+1)).getJSONArray("options");
                question.setOptions(optionsArray.toString());  // 将 JSONArray 转为字符串
            }
            question.setEid(exam.getId());
            questionList.add(question);
        }
        System.out.println(questionList);
        questionService.insertQuestions(questionList);
        return Result.success();
    }

    @Override
    public Result getExamByName(Exam exam) {
        Integer count = examDao.getExamByName(exam);
        return count > 0 ? Result.success() : Result.error();
    }

    @Override
    public void deleteExam(String name) {
        examDao.deleteExam(name);
    }


}
